<?php
/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/7/10 0010
 * Time: 17:12
 */
namespace App\Ordersys\Models;

use App\Base\Models\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cookie;

class OrdersysCartModel extends  BaseModel {
    //use SoftDeletes;
    /**
     * 购物车表名
     * @var string
     */
    public $table="ordersys_cart";
    /**
     * 时间自动
     * @var bool
     */
    public $timestamps=true;
    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'create_time';  //修改添加时间字段
    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'update_time';

    /**
     * 删除
     */
    const DELETED_AT = 'delete_time';
    /**
     * 模型的日期字段保存格式。
     */
    protected $dateFormat = 'U';



    /**
     * 购物车商品总金额
     */
    public $cart_all_price = 0;

    /**
     * 购物车商品总数
     */
    private $cart_goods_num = 0;


    /**
     * 检查购物车内商品是否存在
     *
     * @param
     */
    public function checkCart($condition = array()) {
        return $this->newQuery()->where($condition)->first();
    }

    /**
     * 将商品添加到购物车中
     *
     * @param array $data   商品数据信息
     * @param string $save_type 保存类型，可选值 db,cookie
     * @param int $quantity 购物数量
     */
    public function addCart($data = array(), $save_type = '', $quantity = null) {
        $method = '_addCart'.ucfirst($save_type);
        $insert = $this->$method($data,$quantity);
        //更改购物车总商品数和总金额，传递数组参数只是给DB使用
        $this->getCartNum($save_type,array('buyer_id'=>$data['buyer_id']));

        return $insert;
    }

    /**
     * 购物车加到数据库中去
     * @param array $goods_info
     * @param $quantity
     */
    public function _addCartDb($goods_info = array(),$quantity){

        $condition = array();
        $condition['goods_id'] = $goods_info['id'];
        $condition['buyer_id'] = $goods_info['buyer_id'];
        $check_cart = $this->checkCart($condition);
        if (!empty($check_cart)) return true;
        $array    = array();
        $array['buyer_id']  = $goods_info['buyer_id'];
        $array['goods_id']  = $goods_info['id'];
        $array['goods_name'] = $goods_info['goods_name'];
        $array['goods_price'] = $goods_info['goods_price'];
        $array['goods_num']   = $quantity;
        $array['goods_image'] = $goods_info['goods_image'];
        $array['unit'] = $goods_info['unit'];
        return $this->newQuery()->insert($array);
    }

    /**
     * 更新购物车
     * @param   array   $param 商品信息
     */
    public function editCart($data,$condition) {
        $result = $this->newQuery()->where($condition)->update($data);
        $this->getCartNum('db',array('buyer_id'=>$condition['buyer_id']));
        return $result;
    }

    /**
     * 购物车加到cookie中去
     * @param array $goods_info
     * @param null $quantity
     */
    private function _addCartCookie($goods_info = array(), $quantity = null) {
        //去除斜杠
        $cart_str = get_magic_quotes_gpc() ? stripslashes(Cookie::get('cart')) : Cookie::get('cart');
        $cart_str = base64_decode(decrypt($cart_str));
        $cart_array = @unserialize($cart_str);
        $cart_array = !is_array($cart_array) ? array() : $cart_array;
        if (count($cart_array) >= 5) return false;
        if (in_array($goods_info['goods_id'],array_keys($cart_array))) return true;
        $cart_array[$goods_info['goods_id']] = array(
            'store_id' => $goods_info['store_id'],
            'goods_id' => $goods_info['goods_id'],
            'goods_name' => $goods_info['goods_name'],
            'goods_price' => $goods_info['goods_price'],
            'goods_image' => $goods_info['goods_image'],
            'goods_num' => $quantity
        );
        Cookie::queue('cart',encrypt(base64_encode(serialize($cart_array))),24*3600);
        return true;
    }



    /**
     * 删除购物车商品
     *
     * @param string $type 存储类型 db,cookie
     * @param unknown_type $condition
     */
    public function delCart($type, $condition) {

        if ($type == 'db') {
            $result =  $this->newQuery()->where($condition)->delete();
        } elseif ($type == 'cookie') {
            $cart_str = get_magic_quotes_gpc() ? stripslashes( Cookie::get('cart')) : Cookie::get('cart');
            $cart_str = base64_decode(decrypt($cart_str));
            $cart_array = @unserialize($cart_str);
            if (key_exists($condition['goods_id'],(array)$cart_array)) {
                unset($cart_array[$condition['goods_id']]);
            }
            $cookies_expire =3600 * 24 ;  //cookie 进期时间
            Cookie::queue('admin_uid',encrypt(base64_encode(serialize($cart_array))), $cookies_expire);  //cookie购物车列表
            $result = true;
        }
        //重新计算购物车商品数和总金额
        if ($result) {
            $this->getCartNum($type,array('buyer_id'=>$condition['buyer_id']));
        }
        return $result;
    }


    /**
     * 计算购物车总商品数和总金额
     * @param string $type 购物车信息保存类型 db,cookie
     * @param array $condition 只有登录后操作购物车表时才会用到该参数
     */
    public function getCartNum($type, $condition = array()) {

        if ($type == 'db') {
            $cart_all_price = 0;
            $cart_goods = $this->listCart('db',$condition);
            $this->cart_goods_num = count($cart_goods);
            if(!empty($cart_goods) && is_array($cart_goods)) {
                foreach ($cart_goods as $val) {
                    $cart_all_price += $val['goods_price'] * $val['goods_num'];
                }
            }
            $this->cart_all_price = ncPriceFormat($cart_all_price);
        } elseif ($type == 'cookie') {
            $cart_str = get_magic_quotes_gpc() ? stripslashes(Cookie::get('cart')) : Cookie::get('cart');
            $cart_str = base64_decode(decrypt($cart_str));
            $cart_array = @unserialize($cart_str);
            $cart_array = !is_array($cart_array) ? array() : $cart_array;
            $this->cart_goods_num = count($cart_array);
            $cart_all_price = 0;
            foreach ($cart_array as $v){
                $cart_all_price += floatval($v['goods_price'])*intval($v['goods_num']);
            }
            $this->cart_all_price = $cart_all_price;
        }
        Cookie::queue('cart_goods_num',$this->cart_goods_num,2*3600);  //cookie购物车列表
        return $this->cart_goods_num;
    }


    /**
     * 购物车列表
     *
     * @param string $type 存储类型 db,cookie
     * @param unknown_type $condition
     * @param int $limit
     */
    public function listCart($type, $condition = array(), $limit = '') {

        if ($type == 'db') {

            $cart_list = $this->newQuery()->where($condition)->get();

        } elseif ($type == 'cookie') {
            //去除斜杠
            $cart_str = get_magic_quotes_gpc() ? stripslashes(Cookie::get('cart')) : Cookie::get('cart');
            $cart_str = base64_decode(decrypt($cart_str));
            $cart_list = @unserialize($cart_str);
        }

        $cart_list = is_array($cart_list) ? $cart_list : $cart_list->toArray();
        //顺便设置购物车商品数和总金额
        $this->cart_goods_num =  count($cart_list);
        $cart_all_price = 0;
        if(is_array($cart_list)) {
            foreach ($cart_list as $val) {
                $cart_all_price += $val['goods_price'] * $val['goods_num'];
            }
        }
        $this->cart_all_price = ncPriceFormat($cart_all_price);
        return !is_array($cart_list) ? array() : $cart_list;
    }
}
